<?php
include_once("$config[webroot]/includes/page_utf_class.php");

if($_GET['operation']=="add" or $_GET['operation']=="edit")
{
    if($_POST['act'])
    {
        unset($_GET['s']);
        unset($_GET['m']);
        unset($_GET['operation']);
        
        $pic='';
        $img=[];
        $_POST['pic']=array_unique($_POST['pic']);
        if(!empty($_POST['pic']))
        {
            foreach($_POST['pic'] as $key=>$val)
            {
                if($val)
                {
                    $img[] = array(
                        'src'   =>$val,
                        'param' =>array(
                            'side'      =>$_POST['pic_param_size'][$key],
                            'right'     =>$_POST['pic_param_right'][$key],
                            'bottom'    =>$_POST['pic_param_bottom'][$key]
                        )
                    );
                }
            }
            if(!empty($img))
            {
                $pic=json_encode($img);
            }
        }
        
        //添加活动
        if($_POST["act"]=='save')
        {
            $sql = "insert into ".MICROSHOPEXPANDMATERIAL." (`title`,`pic`,`status`) values('{$_POST['title']}','{$pic}','{$_POST['status']}')";
        }
        //修改活动
        if($_POST["act"]=='edit' and is_numeric($_POST['id']))
        {
            $sql = "update ".MICROSHOPEXPANDMATERIAL." set title='{$_POST['title']}',pic='{$pic}',status='{$_POST['status']}' where id={$_POST['id']}";
            unset($_GET['editid']);
        }
        $db->query($sql);
        
        $getstr=implode('&',convert($_GET));
        msg("?m=micro_shop&s=expand_material.php&$getstr");
    }
    //活动信息
    if($_GET['editid'] and is_numeric($_GET['editid']))
    {
        $sql="select * from ".MICROSHOPEXPANDMATERIAL." where id='$_GET[editid]'";
        $db->query($sql);
        $de=$db->fetchRow();
        
        $picArr = empty($de['pic']) ? [] : json_decode($de['pic'],true);
        
        foreach ($picArr as $v)
        {
            $de['picArr'][] = $v['src'];
            $de['picParam'][] = $v['param'];
        }
    }
}else{
    //获取列表
    $where = "";
    if(($_GET['statu']!="") && ($_GET['statu']>=0)){
        $where .=" and status='$_GET[statu]'";
    }else{
        $where .=" and status>-9";
    }

    $sql="select * from ".MICROSHOPEXPANDMATERIAL." where 1".$where." order by id desc";
    $page = new Page;
    $page->listRows=20;
    //分页
    if (!$page->__get('totalRows'))
    {
        $db->query($sql);
        $page->totalRows = $db->num_rows();
    }
    $sql .= "  limit ".$page->firstRow.",".$page->listRows;
    $db->query($sql);
    $de['list']=$db->getRows();

    $de['page']=$page->prompt();
}

$condTemp = $_GET;
unset($condTemp['m']);
unset($condTemp['s']);
$cond = "";
if(count($condTemp)){
    $cond = "&".http_build_query($condTemp);
}
$tpl->assign("cond",$cond);
$tpl->assign("de",$de);
$tpl->assign("config",$config);
$tpl->display('expand_material.htm');